package org.example.nio;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 邓天天
 * @date 2021/4/4 15:31
 */
public class BioServer {
    public static void main(String[] args) throws Exception{
        final ExecutorService executorService = Executors.newCachedThreadPool();
        final ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了");
        while (true) {
            // 监听
            final Socket accept = serverSocket.accept();
            System.out.println("有一个客户段连接了");
            executorService.execute(()->func(accept));
        }
    }

    private static void func(Socket accept) {
        try(final InputStream inputStream = accept.getInputStream()) {
            String name = Thread.currentThread().getName();
            System.out.println("当前通讯线程的id为"+name);
            char[] bytes = new char[1024];
            // 这里是GBK是因为我本机的telnet的编码是GBK
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"GBK");
            int read = 0;
            while ((read = (inputStreamReader.read(bytes)) )!= -1) {
                System.out.println(name+new String(bytes,0,read));
            }
        }catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}
